﻿var Views = Views || {};
Views.Movie = Views.Movie || {};

Views.Movie.Detail = function () {
    "use strict";

    var origEmployeeList = [];

    var listAction = {
        none: 0,
        assign: 1,
        edit: 2,
        unassign: 3
    };

    var openEmployeeDialog = function (action) {
        var d = $("#DetailDialog").dialog({ autoOpen: false,
            draggable: false,
            modal: true,
            resizable: false,
            width: 600
        });
        d.find("input[type='button']").bind("click", function (e) {
            onEditDialogClick();
        });
        d.find("#DialogAction").val(action);
        d.find("#DialogError").text("");
        d.dialog("open");
    }

    var assignEmployee = function () {
        //init and open dialog
        $("#EmployeeList option[0]").select();
        $("#JobTitleList option[0]").select();
        openEmployeeDialog(listAction.assign);
    }

    var onEditDialogClick = function () {
        var row = null;
        var existingRow = null;
        var empId = $("#EmployeeList").val();
        var empName = $("#EmployeeList option:selected").html();
        var jtId = $("#JobTitleList").val();
        var jtTitle = $("#JobTitleList option:selected").html();
        var action = parseInt($("#DialogAction").val());

        //validate for existing VISIBLE row with same values, kick out if found
        var valid = true;

        if ($("tbody.employeeRows tr[data-employee-id=" + empId + "][data-job-title-id=" + jtId + "][data-action!=" + listAction.unassign + "]").length > 0)
            valid = false;

        if (valid === true) {
            //get existing row if exists
            existingRow = $("tbody.employeeRows tr[data-employee-id=" + empId + "][data-job-title-id=" + jtId + "]");

            if (existingRow.length === 0) {
                if (action === listAction.edit) {
                    //if updating record that doesn't exist previously
                    //mark currently edited row as delete and hide
                    row = $("tbody.employeeRows tr[data-employee-id=" + $("#CurEmployeeId").val() + "][data-job-title-id=" + $("#CurJobTitleId").val() + "]");
                    row.hide();
                    row.attr("data-action", listAction.unassign);
                }

                //since record doesn't exist previously create it from template
                row = $("#employeeTemplate tr").clone();
                setRowEvents(row);
                $("tbody.employeeRows").append(row);
            } else {
                //set existing row as row to use
                row = existingRow;
            }

            //set attributes and copy needed
            row.attr("data-employee-id", empId)
               .attr("data-job-title-id", jtId)
               .attr("data-action", action)
               .show();
            $("td:eq(0)", row).html(empName);
            $("td:eq(1)", row).html(jtTitle);

            $("#DetailDialog").dialog("close");

            sortTable();
        } else {
            $("#DialogError").text("Must be unique name/job combination");
        }
    }

    var unassignEmployee = function (event) {
        var row = $(event.target).parent().parent();

        //hide visibility of row in question, change action to delete, sort table
        row.hide();
        row.attr("data-action", listAction.unassign);
        sortTable();
    }

    var updateEmployee = function (event) {
        var row = $(event.target).parent().parent();
        var empId = row.attr("data-employee-id");
        var jtId = row.attr("data-job-title-id");

        //init and open dialog
        $("#EmployeeList").val(empId);
        $("#JobTitleList").val(jtId);
        $("#CurEmployeeId").val(empId);
        $("#CurJobTitleId").val(jtId);
        openEmployeeDialog(listAction.edit);
    }

    var onFormSubmit = function () {
        //serialize employees list for back-end
        console.log("onFormSubmit fired");

        var rows = $("tbody.employeeRows tr");
        var row = null;
        //var empId = 0;
        //var jtId = 0;
        var key = "";
        var action = 0;
        var origItem = null;
        var commands = "";

        $.each(rows, function (i, e) {
            row = $(e);
            //empId = row.attr("data-employee-id");
            //jtId = row.attr("data-job-title-id");
            key = row.attr("data-employee-id") + "-" + row.attr("data-job-title-id");
            action = parseInt(row.attr("data-action"));
            origItem = origEmployeeList[key];

            if (origItem !== undefined
               && action === listAction.unassign) {
                //if item originally exists and marked "unassign", process for delete
                commands += key + "-" + listAction.unassign + ",";
            } else if (origItem === undefined) {
                //if item originally doesn't exist, process for insert
                commands += key + "-" + listAction.assign + ",";
            }
        });

        //remove trailing "," and push value to hidden field
        commands = commands.substring(0, (commands.length - 1));
        $("#EmployeeChangeList").val(commands);
    }

    var setRowEvents = function (row) {
        row.find(".editLink").bind("click", function (e) {
            e.preventDefault();
            updateEmployee(e);
        });

        row.find(".deleteLink").bind("click", function (e) {
            e.preventDefault();
            unassignEmployee(e);
        });
    }

    var sortTable = function () {
        var rows = $("tbody.employeeRows tr");

        //sort by job title
        rows.sort(function (a, b) {
            var colVal1 = $(a).find("td:eq(1)").text().toLowerCase();
            var colVal2 = $(b).find("td:eq(1)").text().toLowerCase();
            var sr = 0;

            if (colVal1 < colVal2) {
                sr = -1;
            } else if (colVal1 > colVal2) {
                sr = 1
            }

            return sr;
        });

        //sort by employee name
        rows.sort(function (a, b) {
            var colVal1 = $(a).find("td:eq(0)").text().toLowerCase();
            var colVal2 = $(b).find("td:eq(0)").text().toLowerCase();
            var sr = 0;

            if (colVal1 < colVal2) {
                sr = -1;
            } else if (colVal1 > colVal2) {
                sr = 1
            }

            return sr;
        });

        $("tbody.employeeRows").append(rows);
    }

    //public
    var Detail = {};

    Detail.start = function () {
        //setup event handling for add link
        $(".addLink").bind("click", function (e) {
            e.preventDefault();
            assignEmployee();
        });

        //setup event handling for add link
        $("form").bind("submit", function (e) {
            //e.preventDefault();
            onFormSubmit();
        });

        var rows = $(".employeeRows tr");
        var row = null;
        var empId = 0;
        var jtId = 0;

        $.each(rows, function (i, o) {
            row = $(o);
            //setup event handlers on each row's links
            setRowEvents(row);
            //build original set list for concurrency check during save
            empId = row.attr("data-employee-id");
            jtId = row.attr("data-job-title-id");
            origEmployeeList[empId + "-" + jtId] = {
                employeeId: parseInt(row.attr("data-employee-id")),
                jobTitleId: parseInt(row.attr("data-job-title-id"))
            };
        });

        sortTable();
    }

    return Detail;
}
